package net.techwatch.fsindex.listener;

import net.techwatch.fsindex.FileSystemObject;
import net.techwatch.fsindex.dao.FileSystemDao;
import net.techwatch.fsindex.event.FileSystemEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * @author wiv
 *
 */
public class MonitoringListener implements FileSystemListener {

	private Log log = LogFactory.getLog(MonitoringListener.class);
	
	/**
	 * 
	 */
	private FileSystemDao dataManager = null;
	
	/**
	 * Default constructor
	 */
	public MonitoringListener() {
		// nothing to do
	}
	
	/**
	 * @param dataManager
	 */
	public MonitoringListener(FileSystemDao dataManager) {
		this.dataManager = dataManager;
	}
	
	/**
	 * @return
	 */
	public FileSystemDao getFileSystemDao() {
		return this.dataManager;
	}
	
	/**
	 * @param dataManager
	 */
	public void setFileSystemDao(FileSystemDao dataManager) {
		this.dataManager = dataManager;
	}
	
	/* (non-Javadoc)
	 * @see eu.curia.pex.objectloader.fs.FileSystemListener#onCreate(eu.curia.pex.objectloader.fs.FileSystemEvent)
	 */
	public void onCreate(FileSystemEvent event) {
		if(log.isDebugEnabled())
			log.debug("Create event on file object " + event.getParentPath() + "/" + event.getName());
		
		FileSystemObject fileObj = new FileSystemObject();
		fileObj.setFile(event.isFile());
		fileObj.setLastUpdate(event.getLastUpdate());
		fileObj.setParent(event.getParentId());
		fileObj.setPath(event.getParentPath() + "/" + event.getName());
		
		dataManager.create(fileObj);
		
		// set the id in the event
		event.setId(fileObj.getId());
	}

	/* (non-Javadoc)
	 * @see eu.curia.pex.objectloader.fs.FileSystemListener#onDelete(eu.curia.pex.objectloader.fs.FileSystemEvent)
	 */
	public void onDelete(FileSystemEvent event) {
		if(log.isDebugEnabled())
			log.debug("Delete event on file object " + event.getId());
		
		dataManager.remove(event.getId());
	}

	/* (non-Javadoc)
	 * @see eu.curia.pex.objectloader.fs.FileSystemListener#onUpdate(eu.curia.pex.objectloader.fs.FileSystemEvent)
	 */
	public void onUpdate(FileSystemEvent event) {
		if(log.isDebugEnabled())
			log.debug("Update event on file object " + event.getParentPath() + "/" + event.getName());

		dataManager.update(event.getId(), event.getLastUpdate());
	}

}
